package cn.mazexal.examapi.models.converter;

import cn.mazexal.examapi.models.db.ExamQuestionDO;
import cn.mazexal.examapi.models.vo.ExamQuestionVO;
import cn.mazexal.examapi.models.vo.UserExamCollectQuestionVO;
import cn.mazexal.examapi.models.vo.UserExamWrongQuestionVO;
import cn.mazexal.examapi.models.vo.UserQuestionVO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: Mazexal
 * Date: 2025/5/12
 */
@Mapper(componentModel = "spring")
public interface ExamQuestionConverter {

    static final Pattern pattern = Pattern.compile("<option>(.*?)</option>");

    @Mapping(source = "questionOptions", target = "questionOptions", qualifiedByName = "translateOptions")
    ExamQuestionVO toView(ExamQuestionDO examQuestionDO);

    UserExamCollectQuestionVO toCollectView(ExamQuestionVO examQuestionVO);

    UserExamWrongQuestionVO toWrongView(ExamQuestionVO examQuestionVO);

    UserQuestionVO toUserQuestionVO(ExamQuestionVO item);

    @Named("translateOptions")
    default List<String> translateOptions(String questionOptions) {
        /**
         * <option>A </option>
         * <option>B </option>
         * <option>C</option>
         * <option>D </option>
         */
        // 将上面字符串转为 List, 取出option内容
        // 使用正则
        if (questionOptions == null) {
            return null;
        }
        List<String> options = new ArrayList<>();
        Matcher matcher = pattern.matcher(questionOptions);
        while (matcher.find()) {
            String content = matcher.group(1).trim(); // 去除前后空格
            options.add(content);
        }
        return options;
    }

}
